﻿var dataRoles = "";
var dataDep = "";
$(function () {
    $("#btnAdd").click(function () { add(); });
    $("#btnSave").click(function () { save(); });
    $("#btnDelete").click(function () { deleteMulti(); });
    $("#checkAll").click(function () { checkAll(this) });
    loadRoles();
    loadDeps();
});
//全选
function checkAll(obj) {
    $(".checkboxs").each(function () {
        if (obj.checked == true) {
            $(this).prop("checked", true)

        }
        if (obj.checked == false) {
            $(this).prop("checked", false)
        }
    });
};

//加载用户列表数据
function loadTables(pageindex) {
    $("#tableBody").html("");
    $("#checkAll").prop("checked", false);
    $.ajax({
        type: "GET",
        url: "/Sys/User/GetPagedListToJson?pageindex=" + pageindex + "&_t=" + new Date().getTime(),
        success: function (data) {
            $.each(data.rows, function (i, item) {
                var tr = "<tr>";
                tr += "<td align='center'><input type='checkbox' class='checkboxs' value='" + item.id + "'/></td>";
                tr += "<td>" + item.loginId + "</td>";
                tr += "<td>" + item.userName + "</td>";                
                tr += "<td>" + findRoleNameByRoleId(item.roleId) + "</td>";
                tr += "<td>" + (item.isLock==true?"停用":"正常") + "</td>";                
                tr += "<td><button class='btn btn-info btn-xs' href='javascript:;' onclick='edit(\"" + item.id + "\")'><i class='fa fa-edit'></i> 编辑 </button> <button class='btn btn-danger btn-xs' href='javascript:;' onclick='deleteSingle(\"" + item.id + "\")'><i class='fa fa-trash-o'></i> 删除 </button> </td>"
                tr += "</tr>";
                $("#tableBody").append(tr);
            })
            var elment = $("#grid_paging_part"); //分页插件的容器id
            if (data.rowCount > 0) {
                var options = { //分页插件配置项
                    bootstrapMajorVersion: 3,
                    currentPage: pageindex, //当前页
                    numberOfPages: data.rowCount, //总数
                    totalPages: data.pageCount, //总页数
                    onPageChanged: function (event, oldPage, newPage) { //页面切换事件
                        loadTables(newPage);
                    },
                    itemTexts: function (type, page, current) {
                        switch (type) {
                            case "first": return "首页";
                            case "prev": return "上一页";
                            case "next": return "下一页";
                            case "last": return "末页";
                            case "page": return page;
                        }
                    }
                }
                elment.bootstrapPaginator(options); //分页插件初始化
            }            
        }
    })
}

function loadRoles() {
    $("#RoleId").html("");
    var option = "";

    $.ajax({
        type: "GET",
        url: "/Sys/Role/GetAllListToJson?_t=" + new Date().getTime(),
        success: function (data) {
            $.each(data, function (i, item) {
                option += "<option value='" + item.id + "'>" + item.name + "</option>"
            })            
            dataRoles = data;            
            $("#RoleId").html(option);
            loadTables(1);
        }
    });
}

function loadDeps() {
    $("#DepartmentId").html("");
    var option = "";

    $.ajax({
        type: "GET",
        url: "/Sys/Department/GetAllListToJson?_t=" + new Date().getTime(),
        success: function (data) {
            $.each(data, function (i, item) {
                option += "<option value='" + item.id + "'>" + item.name + "</option>"
            })
            dataDep = data;
            $("#DepartmentId").html(option);
        }
    });
}

function findRoleNameByRoleId(roleId) {
    var html = "";
    $.each(dataRoles, function (i, item) {
        if (item.id == roleId) {
            html = item.name;
            //alert(html);
            return html;
        }
    });
    return html;
}

//新增
function add() {
    $("#Id").val(0);
    $("#Remarks").val("");
    $("#SortIndex").val(0);
    $("#LoginId").val("");
    $("#Password").val("");
    $("#UserName").val("");
    $("#EMail").val("");
    $("#MobileNumber").val("");   
    $("#DepartmentId").val(4);   
    $("#RoleId").val("");
    $("#IsLock").prop("checked", false);
    $("#LoginTimes").val(0);

    $("#Title").text("新增用户");
    //弹出新增窗体
    $("#editModal").modal("show");
};
//编辑用户
function edit(id) {
    $.ajax({
        type: "Get",
        url: "/Sys/User/GetUserWithRoles?userId=" + id + "&_t=" + new Date().getTime(),
        success: function (data) {
            $("#Id").val(data.user.id);
            $("#SortIndex").val(data.user.sortIndex);
            $("#Remarks").val(data.user.remarks);
            $("#CreatedBy").val(data.user.createdBy);
            $("#CreatedOn").val(data.user.createdOn);
            $("#LoginId").val(data.user.loginId);
            $("#Password").val(data.user.password);
            $("#UserName").val(data.user.userName);
            $("#Email").val(data.user.eMail);
            $("#MobileNumber").val(data.user.mobileNumber);            
            $("#DepartmentId").val(data.user.departmentId);
            $("#RoleId").val(data.user.roleId);
            $("#IsLock").prop("checked", data.user.isLock);
            $("#LoginTimes").val(data.user.loginTimes);
           
            $("#Title").text("编辑用户")
            $("#editModal").modal("show");
        }
    })
};
//保存
function save() {
    
    var postData = {        
        "Id": $("#Id").val(),
        "Remarks": $("#Remarks").val(),
        "SortIndex": $("#Sort").val(),
        "CreatedBy": $("#CreatedBy").val(),
        "CreatedOn": $("#CreatedOn").val(),
        "LoginId": $("#LoginId").val(),
        "UserName": $("#UserName").val(),
        "Password": $("#Password").val(),
        "RoleId": $("#RoleId").val(),
        "IsLock": $("#IsLock").prop('checked'),
        "EMail": $("#Email").val(),
        "MobileNumber": $("#MobileNumber").val(),            
        "DepartmentId": $("#DepartmentId").val(),
        "LastLoginTime": GetTime(),
        "LastLoginIp": "127.0.0.1",
        "LoginTimes": $("#LoginTimes").val()
    };
    $.ajax({
        type: "Post",
        url: "/Sys/User/AddOrModify",
        data: postData,
        success: function (data) {
            if (data.result == "Success") {
                loadTables(1)
                $("#editModal").modal("hide");
            } else {
                layer.tips(data.message, "#btnSave");
            };
        }
    });
};


//批量删除
function deleteMulti() {
    var ids = "";
    $(".checkboxs").each(function () {
        if ($(this).prop("checked") == true) {
            ids += $(this).val() + ","
        }
    });
    ids = ids.substring(0, ids.length - 1);
    if (ids.length == 0) {
        layer.alert("请选择要删除的记录。");
        return;
    };
    //询问框
    layer.confirm("您确认删除选定的记录吗？", {
        btn: ["确定", "取消"]
    }, function () {
        var sendData = { "ids": ids };
        $.ajax({
            type: "Post",
            url: "/Sys/User/DeleteMutiByIds",
            data: sendData,
            success: function (data) {
                if (data.result == "Success") {
                    loadTables(1)
                    layer.closeAll();
                }
                else {
                    layer.alert("删除失败！");
                }
            }
        });
    });
};
//删除单条数据
function deleteSingle(id) {
    layer.confirm("您确认删除选定的记录吗？", {
        btn: ["确定", "取消"]
    }, function () {
        $.ajax({
            type: "POST",
            url: "/Sys/User/DeleteById",
            data: { "id": id },
            success: function (data) {
                if (data.result == "Success") {
                    loadTables(1)
                    layer.closeAll();
                }
                else {
                    layer.alert("删除失败！");
                }
            }
        })
    });
};


function GetTime(date) {
    if (date == null) {
        date = new Date();
    }
    var y = date.getFullYear();
    var M = date.getMonth() + 1;
    var d = date.getDate();
    var h = date.getHours();
    var m = date.getMinutes();
    var s = date.getSeconds();
    //var S = date.getTime() % 1000;
    var html = y + "-";
    if (M < 10) {
        html += "0";
    }
    html += M + "-";

    if (d < 10) {
        html += "0";
    }
    html += d + " ";
    if (h < 10) {
        html += "0";
    }
    html += h + ":";
    if (m < 10) {
        html += "0";
    }
    html += m + ":";
    if (s < 10) {
        html += "0";
    }
    html += s;
    //html += " ";
    //if (S < 100) {
    //    html += "0"
    //}
    //if (S < 10) {
    //    html += "0";
    //}
    //html += S;
    return html;
}